<!--
 * @Descripttion:
 * @version:
 * @Editor: E-CHOOSEUS R&D
 * @LastEditors: E-CHOOSEUS R&D
-->
<template>
  <div v-loading="loading2 || loading" class="intensiveCare">
    <div class="act-bar">
      <div class="date-quick left">
        <el-date-picker
          v-model="activeDate"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="timestamp"
          class="top-datepicker"
          popper-class="noNeedClear"
          :picker-options="pickerOptions"
          :clearable="false"
        />
      </div>
      <img
        class="refresh left ml-10"
        src="@/assets/images/refresh.png"
        @click="reloadData"
      />
      <!-- <el-button type="primary" :disabled="isFlow" @click="handleShowDrawer"
          >新增</el-button
        > -->
      <!-- <el-button
        v-has="'nursingDoc:edit'"
        class="my-btn"
        type="primary"
        @click="handleSave"
        >保 存</el-button
      > -->
      <!-- <CAFileCancel :documentCode="12" moduleCode="nursingDocument" /> -->
      <!-- <el-button v-has="'nursingDoc:export'" type="primary" @click="dzblUpload"
        >电子病历归档</el-button
      > -->
      <el-button
        v-has="'nursingDoc:export'"
        type="primary"
        @click="signWithoutApperance"
        >CA认证</el-button
      >
      <el-button
        v-has="'nursingDoc:export'"
        class="my-btn"
        @click="handleOutput"
        >导 出</el-button
      >
      <el-button v-has="'nursingDoc:export'" class="my-btn" @click="handlePrint"
        >打 印</el-button
      >
      <button ref="printBtn" v-print="printConf" style="display: none"></button>
    </div>
    <div class="multi-container">
      <div id="printDom" ref="printDom" class="printMain">
        <ai-doc-page
          ref="ai-doc-page"
          :username="user.name"
          :activeDate="activeDate"
          :printing="loading"
          @changeLoading2="changeLoading2"
          @getOperationDrawerForm="getOperationDrawerForm"
          @genLastEvalRecord="e => (lastEvalRecord = e)"
          @edit="handleEdit"
        />
      </div>
    </div>
    <!-- <OperationDrawer ref="drawer" :cfgData="cfgData" @update="reloadData" /> -->
    <el-dialog
      title="CA认证二维码"
      :visible.sync="dialogVisible"
      width="500px"
      @close="onClose"
    >
      <div class="imgBox">
        <img :src="'data:image/png;base64,' + base64Url" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { endOfDay, startOfDay } from 'date-fns'
import { Notification } from 'element-ui'
import { pdfExportMulti } from 'internal-web-utils'
import { cloneDeep, flatten } from 'lodash-unified'
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  set,
  toRefs,
  watch
} from 'vue'

import { Doc } from '@/api/doc/index'
import { getCareData as getIcrDocRecordList } from '@/api/manage/doc-IntensiveCareRecord'
import CAFileCancel from '@/components/CAFileCancel/index.vue'
import { useCA } from '@/hooks'
import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import AiDocPage from './aiDocPage.vue'
// import { OperationDrawer } from './components/OperationDrawer'

const nowDate = new Date()

export default defineComponent({
  name: 'IntensiveCare',
  components: {
    AiDocPage,
    CAFileCancel
    // OperationDrawer
  },
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  setup(props) {
    const state = reactive({
      printConf: {
        id: 'printDom',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {
          state.loading = false
        }, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: ''
      },
      tableData: [],
      activeDate: [
        startOfDay(new Date()).getTime() + 8 * 60 * 60 * 1000,
        endOfDay(new Date()).getTime() + 8 * 60 * 60 * 1000
      ],
      loading: false,
      loading2: false,
      base64Url: '',
      dialogVisible: false,
      pickerOptions: {},
      cfgData: [],
      lastEvalRecord: [],
      'ai-doc-page': {},
      printDom: {},
      drawer: {},
      printBtn: {}
    })

    const store = getStoreFromInstance()
    const { $notify } = getElementFnFromInstance()
    const CA = useCA()

    const user = computed(() => store.getters.user)

    const patCur = computed(() => store.getters.patCur)
    const isHistory = computed(() => store.getters.isHistory)
    const isFlow = computed(() => store.getters.isFlow)

    function getOperationDrawerForm({ cfgData }) {
      const noNeedDictValue = ['date_value', 'yx-hljl', 'operater']
      const arr = []
      if (cfgData) {
        cfgData.forEach(item => {
          if (!noNeedDictValue.includes(item.dictValue)) {
            arr.push(item)
          }
        })
      }
      state.cfgData = arr
    }

    function reloadData() {
      state['ai-doc-page'].initData()
    }

    function getParams() {
      return state.tableData
    }

    function handleOutput() {
      state.loading = true
      // this.$nextTick().then(() => {
      setTimeout(() => {
        pdfExportMulti(
          document.querySelectorAll('.pages-row'),
          {
            orientation: 'landscape',
            fileName: '重症护理记录单.pdf',
            scale: 2
          },
          () => {
            state.loading = false
          }
        )
      }, 500)
      // });
    }

    let timer

    // 获取签名-二维码
    function signWithoutApperance() {
      state.loading = true
      const params = {
        patientIdent: patCur.value.patientIdent,
        hospitalNumber: patCur.value.hospitalNumber,
        startTime: state.activeDate[0],
        endTime: state.activeDate[0]
      }
      // 获取签名-二维码
      getIcrDocRecordList(params)
        .then(res => {
          state.loading = false
          return Doc.addSignJob({
            req: {
              documentCode: 'nursingDocument',
              hospitalNumber: patCur.value.hospitalNumber,
              moduleCode: '12',
              patientIdent: patCur.value.patientIdent,
              rkTime: patCur.value.rkTime
            },
            vo: {
              data: btoa(
                unescape(encodeURIComponent(JSON.stringify(res.data)))
              ),
              dataType: 'DATA',
              expiryDate: 5,
              requireQrCode: 'Y'
            }
          })
        })
        .then(res => {
          state.base64Url = res.data.qrCode
          state.dialogVisible = true

          const pollSignStatus = () => {
            querySignJobStatus(res.data.signDataId, timer)
          }

          timer = setInterval(pollSignStatus, 5000)
        })
    }

    // 查询任务状态
    function querySignJobStatus(signDataId, timer) {
      Doc.querySignJob({
        req: {
          documentCode: 12,
          hospitalNumber: patCur.value.hospitalNumber,
          moduleCode: 'nursingDocument',
          patientIdent: patCur.value.patientIdent,
          rkTime: patCur.value.rkTime
        },
        vo: {
          signDataId
        }
      }).then(res => {
        if (res.data.jobStatus == 'FINISH') {
          Notification.success('认证成功！')
          onClose()
          reloadData()
        }
      })
    }

    // 关闭弹窗
    function onClose() {
      clearInterval(timer)
      state.dialogVisible = false
      state.loading = false
    }

    function dzblUpload() {
      state.loading = true
      CA.dzblUpload(
        Object.values(document.querySelectorAll('.pages-row')),
        'landscape',
        '重症护理记录单.pdf',
        'nursingDocument',
        12,
        () => {
          state.loading = false
        }
      )
    }

    function changeLoading2(f) {
      state.loading2 = f
    }

    function handleShowDrawer() {
      state.drawer.openDrawer(state.lastEvalRecord, false)
    }

    function handlePrint() {
      state.loading = true
      nextTick(() => {
        state.printBtn.click()
      })
    }

    function handleSave() {
      state['ai-doc-page'].saveDocData()
    }

    function handleEdit(idx, item) {
      if (isFlow.value) {
        return
      }
      const data = cloneDeep(item).map((v, i) => {
        v.rData[idx].rData.forEach(v2 => {
          if (v2.dictValue === 'yx-crl-in' || v2.dictValue === 'yx-crl-out') {
            let values = [],
              masterIds = [],
              itemCodes = []
            if (v2.val) {
              values = v2.val.split(';')
            }
            if (v2.masterId) {
              masterIds = v2.masterId.split(';')
            }
            if (v2.itemCode) {
              itemCodes = v2.itemCode.split(';')
            }
            const validData = []
            const allowItemCodesIn = ['in_bsl', 'in_kf', 'in_qt']
            values.forEach((v3, index3) => {
              if (v2.dictValue === 'yx-crl-in') {
                if (
                  masterIds[index3] === 'undefined' &&
                  allowItemCodesIn.includes(itemCodes[index3])
                ) {
                  validData.push(v3)
                }
              } else {
                if (masterIds[index3] === 'undefined') {
                  validData.push(v3)
                }
              }
            })
            v2.val = validData.join(';')
          }
        })

        if (i > 0) {
          return v.rData[idx].rData.splice(1)
        }

        return v.rData[idx].rData
      })
      state.drawer.openDrawer(flatten(data))
    }

    watch(
      () => props.data,
      () => {},
      { immediate: true }
    )

    watch(
      patCur,
      val => {
        if (val) {
          if (isHistory.value) {
            const endCkTimeStamp = +new Date(patCur.value.endCkTime)
            state.activeDate[0] = endCkTimeStamp - 24 * 60 * 60 * 1000
            state.activeDate[1] = endCkTimeStamp
          }
        }
      },
      { deep: true, immediate: true }
    )

    return {
      ...toRefs(state),
      user,
      isFlow,
      onClose,
      handleShowDrawer,
      handleOutput,
      handlePrint,
      handleSave,
      changeLoading2,
      getOperationDrawerForm,
      handleEdit,
      reloadData,
      signWithoutApperance,
      dzblUpload
    }
  }
})
</script>
<style lang="scss" scoped>
.intensiveCare {
  height: calc(100% - 15px);
}

.multi-container {
  height: calc(100% - 47px);
  // overflow: auto;
}

.printMain {
  display: inline-block;
  text-align: left;
  background: #fff;
}

.act-bar {
  min-height: 52px;
  margin-bottom: 10px;
  padding: 9px 10px;
  text-align: right;
  border-bottom: 1px solid #f2f4f5;

  .date-quick {
    display: inline-flex;
    align-items: center;
    vertical-align: bottom;
    // border: 1px solid #c8d0e2;
    background: #fff;
    border-radius: 4px;
  }

  .picker-before,
  .picker-after {
    width: 26px;
    height: 30px;
    opacity: 1;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    color: #7d869d;
    background: rgb(22 93 255 / 10%);

    &.disabled {
      cursor: not-allowed;
    }
  }

  .picker-after {
    margin-left: -1px;
    border-radius: 0 4px 4px 0;
  }
}

.refresh {
  width: 32px;
  padding: 8px;
  background: #155ef3;
  border-radius: 4px;
  cursor: pointer;
  vertical-align: top;
}

.imgBox {
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 300px;
  }
}
</style>
